"""
基于MSSQL存储层的主应用文件
"""
from fastapi import FastAPI, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from typing import List, Optional
from datetime import datetime
import logging

from .mssql_signal_service import MSSQLSignalService
from .schemas import (
    SignalCollectionIn, SignalCollectionOut, 
    DeviceInfoIn, DeviceInfoOut, 
    SignalStatisticsOut
)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建FastAPI应用
app = FastAPI(
    title="4G信号检测系统 - MSSQL版本",
    description="基于MSSQL存储的4G信号采集和分析系统",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 创建信号服务实例
signal_service = MSSQLSignalService()

@app.get("/")
async def root():
    """根路径"""
    return {"message": "4G信号检测系统 - MSSQL版本", "status": "running"}

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "timestamp": datetime.utcnow()}

@app.post("/api/signals", response_model=SignalCollectionOut)
async def create_signal_collection(signal_data: SignalCollectionIn):
    """创建信号采集记录"""
    try:
        return signal_service.create_signal_collection(signal_data)
    except Exception as e:
        logger.error(f"创建信号采集记录失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/signals", response_model=List[SignalCollectionOut])
async def get_signal_collections(
    device_id: Optional[str] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    offset: int = 0
):
    """获取信号采集记录列表"""
    try:
        return signal_service.get_signal_collections(
            device_id=device_id,
            start_time=start_time,
            end_time=end_time,
            limit=limit,
            offset=offset
        )
    except Exception as e:
        logger.error(f"获取信号采集记录失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/signals/statistics/{device_id}", response_model=SignalStatisticsOut)
async def get_signal_statistics(device_id: str):
    """获取设备信号统计信息"""
    try:
        statistics = signal_service.get_signal_statistics(device_id)
        if not statistics:
            raise HTTPException(status_code=404, detail="未找到该设备的统计信息")
        return statistics
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取信号统计信息失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/devices", response_model=DeviceInfoOut)
async def register_device(device_info: DeviceInfoIn):
    """注册设备信息"""
    try:
        return signal_service.register_device(device_info)
    except Exception as e:
        logger.error(f"设备注册失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/devices/{device_id}", response_model=DeviceInfoOut)
async def get_device_info(device_id: str):
    """获取设备信息"""
    try:
        # 这里需要添加获取设备信息的方法
        # 暂时返回一个简单的响应
        return {"device_id": device_id, "message": "设备信息获取功能待实现"}
    except Exception as e:
        logger.error(f"获取设备信息失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8886)